package io.gitee.zhangbinhub.admin.authentication

import io.gitee.zhangbinhub.admin.base.BaseAuthenticationConverter
import io.gitee.zhangbinhub.admin.constant.OauthConstant
import jakarta.servlet.http.HttpServletRequest
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames

class OauthUserPasswordAuthenticationConverter : BaseAuthenticationConverter {
    override fun convert(request: HttpServletRequest): Authentication? {
        val grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE)
        if (OauthConstant.granterUserPassword != grantType) {
            return null
        }
        val clientPrincipal = SecurityContextHolder.getContext().authentication
        val parameters = getParameters(request)
        val username = parameters.getFirst(OAuth2ParameterNames.USERNAME)
        val password = parameters.getFirst(OAuth2ParameterNames.PASSWORD)
        val additionalParameters: MutableMap<String, Any> = HashMap()
        parameters.forEach { (key, value) ->
            if (key != OAuth2ParameterNames.GRANT_TYPE &&
                key != OAuth2ParameterNames.USERNAME &&
                key != OAuth2ParameterNames.PASSWORD
            ) {
                additionalParameters[key] = value[0]
            }
        }
        return OauthUserPasswordAuthenticationRequest(
            username,
            password,
            clientPrincipal,
            emptyList(),
            additionalParameters
        )
    }
}